# -*- coding: utf-8 -*-
import atexit
import getopt
import os
import sys
from ss import commands, error, parseopts
from ss.cmdutils import find_repo
from ss.ui import Ui

def run():
    sys.exit(dispatch(sys.argv[1:]))

def dispatch(args):
    ui = Ui()
    return _run_catch(ui, args)

def _run_catch(ui, args):
    try:
        return _dispatch(ui, args)
    except error.CommandError, inst:
        if inst.args[0]:
            ui.warn('ss %s: %s\n' % (inst.args[0], inst.args[1]))
        else:
            ui.warn('ss: %s\n' % inst.args[1])
    except KeyboardInterrupt:
        ui.warn('\ninterrupted!\n')
    except SystemExit, inst:
        return inst.code
    except:
        ui.warn('** unknown exception encountered\n')
        raise
    return -1

def _dispatch(ui, args):
    wd = os.getcwd()
    repo_path = find_repo(wd) or ''
    cmd, func, args, options, cmd_options = _parse(ui, args)

    print cmd, options, cmd_options

    if options['time']:
        def get_times():
            return os.times()
        s = get_times()
        def print_time():
            t = get_times()
            ui.warn('time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n' %
                    (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
        atexit.register(print_time)

def _parse(ui, args):
    opts = {}
    cmd_opts = {}
    try:
        args = parseopts.parse_opts(args, commands.globalopts, opts)
    except getopt.GetoptError, inst:
        raise error.CommandError(None, inst)
    c = []
    if args:
        cmd, args = args[0], args[1:]
    else:
        cmd = None
    for opt in commands.globalopts:
        c.append((opt[0], opt[1], opts[opt[1]], opt[3]))
    try:
        args = parseopts.parse_opts(args, c, cmd_opts)
    except getopt.GetoptError, inst:
        raise error.CommandError(cmd, inst)
    for opt in commands.globalopts:
        name = opt[1]
        opts[name] = cmd_opts[name]
        del cmd_opts[name]
    return cmd, None, args, opts, cmd_opts

